//
//  BalanceHomeViewController.m
//  HuLaQuan
//
//  Created by hok on 1/15/16.
//  Copyright © 2016 Jianghao. All rights reserved.
//

#import "BalanceHomeViewController.h"


//Cells
#import "BalanceHomeCell.h"

//
#import "XLCycleScrollView.h"


//
#import <SDWebImage/UIImageView+WebCache.h>

#import "HomeTabBarController.h"

#import <AVFoundation/AVFoundation.h>
//logic model
#import "GetAdvertisingImageEngine.h"

@interface BalanceHomeViewController ()<XLCycleScrollViewDatasource,XLCycleScrollViewDelegate>

@property (weak, nonatomic) IBOutlet UIView *cardView;
@property (weak, nonatomic) IBOutlet UIView *scanView;

@property (strong, nonatomic) XLCycleScrollView *xlscrollView;
@property (nonatomic, strong) NSArray *adImageURLs;

@property (weak, nonatomic) IBOutlet UICollectionView *functionItemsView;
@property (strong, nonatomic) NSArray *items;


@property (weak, nonatomic) IBOutlet UIView *bottomView;

//logic model
@property(nonatomic,strong)GetAdvertisingImageEngine *adImageEngine;

@end


static NSString * const BalanceItemsCellIdentifier = @"BalanceItemsCell";

@implementation BalanceHomeViewController

-(GetAdvertisingImageEngine *)adImageEngine
{
    if (!_adImageEngine) {
        
        _adImageEngine = [[GetAdvertisingImageEngine alloc]init];
    }
    return _adImageEngine;
}

- (NSArray *)items
{
    if(!_items) _items=[NSMutableArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"BalanceHomeItems" ofType:@"plist"]];
    return _items;
}
#pragma mark - 设置页面
- (void)setupUI
{
    self.title = @"首页";
    
    [self.functionItemsView registerNib:[BalanceHomeCell nib] forCellWithReuseIdentifier:BalanceItemsCellIdentifier];
    self.functionItemsView.backgroundColor = [UIColor whiteColor];
    
    UIImage* img1=[[UIImage imageNamed:@"yinlian_home"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    UIBarButtonItem*barItem1 = [[UIBarButtonItem alloc]
                                initWithImage:img1
                                style:UIBarButtonItemStylePlain
                                target:self
                                action:nil];
    self.navigationItem.leftBarButtonItem = barItem1;
    
    
    UITapGestureRecognizer *gestureRecognizershowScanView = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showScanView:)];
    UITapGestureRecognizer *gestureRecognizershowCardView = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showCardView:)];
    
    
    [self.scanView addGestureRecognizer:gestureRecognizershowScanView];
    [self.cardView addGestureRecognizer:gestureRecognizershowCardView];
    
    
    /**
     *  广告位
     */
   // [self.adImageEngine getAdverttisingImage:@""];
    
    
}

- (void)setupAdImageScrollView
{
    
    
    
    /* [self.adScrollView initWithCount:self.adImageURLs.count delegate:self];
     self.adScrollView.scrollInterval = 2.0f;
     
     // adjust pageControl position
     self.adScrollView.pageControlPosition = ICPageControlPosition_BottomLeft;
     
     // hide pageControl or not
     self.adScrollView.hidePageControl = NO;*/
    
    // self.adImageURLs =@[@"ad1_balance_home",@"ad2_balance_home"];
    
    CGRect frame = self.bottomView.bounds;
      frame.size.width = SCREEN_WIDTH;
//    if (self.xlscrollView) {
//        [self.xlscrollView removeFromSuperview];
//        self.xlscrollView = nil;
//    }
    if(!self.xlscrollView){
        XLCycleScrollView *csView = [[XLCycleScrollView alloc] initWithFrame:frame];
        csView.delegate = self;
        csView.datasource = self;
        self.xlscrollView = csView;
        [self.bottomView addSubview:self.xlscrollView];
        
        self.xlscrollView.delegate = self;
        self.xlscrollView.datasource = self;
    }
    
    
}


#pragma mark - XL delegate
- (NSInteger)numberOfPages
{
    return [self.adImageURLs count];
}

- (UIView *)pageAtIndex:(NSInteger)index
{
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:self.xlscrollView.frame];
    if ([self.adImageURLs count]) {

        @try {
            
           // NSLog(@"url -- %@",self.adImageURLs[index][@"bannerpic"][@"pic0"]);
            [imageView sd_setImageWithURL:self.adImageURLs[index][@"bannerpic"]
                         placeholderImage:[UIImage imageNamed:@"placeholder_home"]
                                completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {if
                                    (error){
                                        //NSLog(@"error %@ %@",[error description],imageURL);
                                    }else{
                                        
                                    }
                                }];

            
            
        }
        @catch (NSException *exception) {
            //NSLog(@"%@",exception);
        }
        @finally {
            
        }
        
    }else{
        imageView.image = [UIImage imageNamed:@"placeholder_home"];
    }
    
    /* NSLog(@"-- %f",self.view.bounds.size.width);
     l.text = [NSString stringWithFormat:@"%d",index];
     l.font = [UIFont systemFontOfSize:72];
     l.textAlignment = UITextAlignmentCenter;
     l.backgroundColor = [UIColor blackColor];*/
    return imageView;
}

- (void)didClickPage:(XLCycleScrollView *)csView atIndex:(NSInteger)index
{
    if (index == 0) {
        [self performSegueWithIdentifier:@"ShowPhoneRecharge" sender:self];
    }
    /*UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil
     message:[NSString stringWithFormat:@"当前点击第%d个页面",index]
     delegate:self
     cancelButtonTitle:@"确定"
     otherButtonTitles:nil];
     [alert show];*/
}


#pragma mark - UICollectionViewDataSource
//定义展示的UICollectionViewCell的个数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{

    return self.items.count;

    
}
//定义展示的Section的个数
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

//每个UICollectionView展示的内容
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    if ([collectionView isEqual:self.functionItemsView]) {
        BalanceHomeCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:BalanceItemsCellIdentifier forIndexPath:indexPath];
       // [cell sizeToFit];
        
        
        
        if (IS_IPHONE_6P) {

            cell.imageWidth.constant = cell.imageWidth.constant * 1.3;
            cell.imageHeight.constant = cell.imageHeight.constant * 1.3;
            cell.imageTop.constant = cell.imageTop.constant - 3;
            cell.itemTitle.font =  [UIFont fontWithName:FONT_NAME size:15];
        }
        
        cell.indexPath = indexPath;
        cell.itemTitle.text = self.items[indexPath.row][@"title"];
        cell.itemImageName = self.items[indexPath.row][@"image"];
        
        
        
        // //NSLog(@"booj %@ %d %@",self.items[indexPath.row][@"title"],indexPath.row, self.items[indexPath.row][@"image"]);
     /*   if ([self.items[indexPath.row][@"title"] isEqualToString:@"待审核"]) {
            if ([[[NSUserDefaults standardUserDefaults] valueForKey:@"UserUncheckedOrder"] boolValue] ) {
                cell.redAlertPointView.hidden = NO;
            }else{
                cell.redAlertPointView.hidden = YES;
            }
            
        }
        if ([self.items[indexPath.row][@"title"] isEqualToString:@"预约记录"])
        {
            if ([[[NSUserDefaults standardUserDefaults] valueForKey:@"UserUncheckedBigOrder"] boolValue] ) {
                cell.redAlertPointView.hidden = NO;
            }else{
                cell.redAlertPointView.hidden = YES;
            }
        }*/
        
        return cell;
    }
    
    return nil;
    
}
//定义每个UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(self.functionItemsView.bounds.size.width /3, self.functionItemsView.bounds.size.height /3);
    
    
}
//定义每个UICollectionView 的间距
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0, 0, 0, 0);
}


//返回这个UICollectionView是否可以被选择
-(BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}
#pragma mark - UICollectionViewDelegate
//UICollectionView被选中时调用的方法
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
   // NSLog(@"select %d",indexPath.row);
    
  //  UIStoryboard *convPayStoryBoard = [UIStoryboard storyboardWithName:@"ConvenientPay" bundle:nil];
    
    switch (indexPath.row) {
        case 2:
        {
            
            [self performSegueWithIdentifier:@"ShowWaterPay" sender:self];
        }
//            [self performSegueWithIdentifier:@"ShowCardLifeFakeViewController" sender:self];
            break;
        case 0:
            [self performSegueWithIdentifier:@"ShowFMRadioStoryboard" sender:self];
            break;
        case 3:
            [self performSegueWithIdentifier:@"ShowGasPay" sender:self];
            break;
        case 1:
            [self performSegueWithIdentifier:@"ShowElectricityPay" sender:self];
            break;
        case 4:
            [self performSegueWithIdentifier:@"ShowPhoneRecharge" sender:self];
            break;
        case 5:
            [self performSegueWithIdentifier:@"ShowTraficFinePay" sender:self];
            break;
        case 6:
            [self performSegueWithIdentifier:@"ShowParking" sender:self];
            break;
        default:
            break;
    }
    
    
}
//显示账单列表
- (IBAction)tapPaymentListButton:(id)sender {
    [self performSegueWithIdentifier:@"ShowPaymentListStoryboard" sender:self];
}


#pragma mark - Tap Gusture Events

//扫描
- (void)showScanView:(UITapGestureRecognizer *)sender
{
    // NSLog(@"scan");
    
    NSString *mediaType = AVMediaTypeVideo;// Or AVMediaTypeAudio
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
    //NSLog(@"---cui--authStatus--------%d",authStatus);
    
    if(authStatus ==AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied){
        //NSLog(@"Denied");     //应该是这个，如果不允许的话
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                        message:@"请在设备的\"设置-隐私-相机 \"中允许访问相机。"
                                                       delegate:self
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
        return;
        
        
    }
    else if(authStatus == AVAuthorizationStatusAuthorized){//允许访问
        // The user has explicitly granted permission for media capture, or explicit user permission is not necessary for the media type in question.
        //NSLog(@"Authorized");
        dispatch_async(dispatch_get_main_queue(), ^{
            [self performSegueWithIdentifier:@"ShowScanCodeStoryboard" sender:self];
        });
        return;
        
    }else if(authStatus == AVAuthorizationStatusNotDetermined){
        // Explicit user permission is required for media capture, but the user has not yet granted or denied such permission.
        [AVCaptureDevice requestAccessForMediaType:mediaType completionHandler:^(BOOL granted) {
            if(granted){//点击允许访问时调用
                //用户明确许可与否，媒体需要捕获，但用户尚未授予或拒绝许可。
                //NSLog(@"Granted access to %@", mediaType);
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self performSegueWithIdentifier:@"ShowScanCodeStoryboard" sender:self];
                });
                
            }
            else {
                //NSLog(@"Not granted access to %@", mediaType);
            }
            
        }];
    }else {
        //NSLog(@"Unknown authorization status");
    }

    
}
//显示银行卡信息
- (void)showCardView:(UITapGestureRecognizer *)sender
{
    NSLog(@"card");
    [self performSegueWithIdentifier:@"ShowBankCardListFromHome" sender:self];
    
}

#pragma mark - call back

/**
 *  获取广告位
 *
 *  @return <#return value description#>
 */
- (void)getADImageFinish:(NSNotification*) notification
{
    
    [YuNetworkStatusUtilities dismissHUD];
    NSDictionary *messageDic = [notification object];//获取到传递的对象
    if ([messageDic[@"isSuccess"] boolValue]) {
        NSLog(@"%@",messageDic[@"result"]);
        if ([messageDic[@"result"] isKindOfClass:[NSArray class]]) {
            self.adImageURLs = messageDic[@"result"];
        }else{
            self.adImageURLs = @[messageDic[@"result"]];
        }
        
       [self setupAdImageScrollView];
    }else{
        [self showNetWorkError:messageDic[@"message"]];
        
    }
    
}


#pragma mark - life cycle

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    [(HomeTabBarController *)self.tabBarController setTabBarHidden:NO];
    
    self.tabBarController.tabBar.hidden = NO;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getADImageFinish:) name:@"GetADImageFinish" object:nil];
    
    
    
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:YES];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"GetADImageFinish" object:nil];
}
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    
    [(HomeTabBarController *)self.tabBarController setTabBarHidden:YES];
}
@end
